<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        if ($this->auth->is_logged_in() == false) {
            $this->login();
        } else {
            $this->template->set('title', 'Welcome user! | MyWebApplication.com');
            // tampilkan halaman dashboard dengan data menu 
            $this->template->load('template', 'admin/index');
        }
    }

    public function manajemen_menu() {
        // mencegah user yang belum login untuk mengakses halaman ini
        $this->auth->restrict();
        // mencegah user mengakses menu yang tidak boleh ia buka
        $this->auth->cek_menu(1);
        // tampilkan isi menu manajemen menu (mungkin tabel menu/input form menu)
        $this->template->set('title', 'Manajemen User | MyWebApplication.com');
        $this->template->load('template', 'admin/manajemen_menu');
    }

    public function login() {
        $this->load->library('form_validation');
        // load helper captcha
        $this->load->helper('captcha');
        // buat captcha 
        $data['captcha'] = $this->_set_captcha();

        $this->form_validation->set_rules('username', 'Username', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        // validasi form untuk captcha
        $this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|callback_valid_captcha');

        $this->form_validation->set_error_delimiters(' <span style="color:#FF0000">', '</span>');

        if ($this->form_validation->run() == FALSE) {
            $this->template->set('title', 'Login Form | MyWebApplication.com');
            $this->template->load('template', 'admin/login_form', $data);
        } else {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $success = $this->auth->do_login($username, $password);
            if ($success) {
                // lemparkan ke halaman index user
                redirect('home/index');
            } else {
                $this->template->set('title', 'Login Form | MyWebApplication.com');
                $data['login_info'] = "Maaf, username dan password salah!";
                $this->template->load('template', 'admin/login_form', $data);
            }
        }
    }

    private function _set_captcha() {
        $this->load->helper('string');
        $vals = array(
            'img_path' => './asset/captcha/',
            'img_url' => base_url() . '/asset/captcha/',
            'img_width' => '120',
            'img_height' => 30,
            'expiration' => 7200,
            'word' => random_string('numeric', 6)
        );

        $cap = create_captcha($vals);

        $data = array(
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']
        );

        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);
        return $cap;
    }

    function valid_captcha($str) {
        // First, delete old captchas
        $expiration = time() - 7200; // Two hour limit
        $this->db->query("DELETE FROM captcha WHERE captcha_time < " . $expiration);

        // Then see if a captcha exists:
        $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
        $binds = array($str, $this->input->ip_address(), $expiration);
        $query = $this->db->query($sql, $binds);
        $row = $query->row();

        if ($row->count == 0) {
            $this->form_validation->set_message('valid_captcha', 'Capctha tidak valid');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function logout() {
        if ($this->auth->is_logged_in() == true) {
            // jika dia memang sudah login, destroy session
            $this->auth->do_logout();
        }
        // larikan ke halaman utama
        redirect('home');
    }

    function manajemen_user() {
        // mencegah user yang belum login untuk mengakses halaman ini
        $this->auth->restrict();
        // mencegah user mengakses menu yang tidak boleh ia buka (manejemen user menu_id = 2)
        $this->auth->cek_menu(2);

        // get data dari usermodel
        $data['all_user'] = $this->usermodel->get_all_user();
        $this->template->set('title', 'Manajemen User | MyWebApplication.com');
        // load view tabel_user.php di folder application/views/admin/
        $this->template->load('template', 'admin/tabel_user', $data);
    }

    function insert_user() {
        // mencegah user yang belum login untuk mengakses halaman ini
        $this->auth->restrict();
        // mencegah user mengakses menu yang tidak boleh ia buka (manejemen user menu_id = 2)
        $this->auth->cek_menu(2);

        $this->load->library('form_validation');

        $this->form_validation->set_rules('nama', 'nama', 'trim|required');
        $this->form_validation->set_rules('username', 'Username', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        $this->form_validation->set_rules('password_conf', 'Password Confirmation', 'trim|required|matches[password]');
        $this->form_validation->set_rules('level', 'Level', 'trim|required');

        $this->form_validation->set_error_delimiters(' <span style="color:#FF0000">', '</span>');

        if ($this->form_validation->run() == FALSE) {
            $data['level'] = $this->usermodel->get_all_level();
            $this->template->set('title', 'Tambah User Baru | MyWebApplication.com');
            $this->template->load('template', 'admin/form_input_user', $data);
        } else {
            $data_user = array(
                'user_nama' => $this->input->post('nama'),
                'user_username' => $this->input->post('username'),
                'user_password' => md5($this->input->post('password')),
                'user_level' => $this->input->post('level')
            );
            $this->usermodel->insert_data_user($data_user);
            // kembalikan ke halaman manajemen user
            redirect('home/manajemen_user');
        }
    }

    function edit_user() {
        // mencegah user yang belum login untuk mengakses halaman ini
        $this->auth->restrict();
        // mencegah user mengakses menu yang tidak boleh ia buka (manejemen user menu_id = 2)
        $this->auth->cek_menu(2);

        $this->load->library('form_validation');

        $this->form_validation->set_rules('nama', 'nama', 'trim|required');
        $this->form_validation->set_rules('username', 'Username', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        $this->form_validation->set_rules('password_conf', 'Password Confirmation', 'trim|required|matches[password]');
        $this->form_validation->set_rules('level', 'Level', 'trim|required');

        $this->form_validation->set_error_delimiters(' <span style="color:#FF0000">', '</span>');

        // dapatkan id user dari segment ke-3 dari URI
        $id = $this->uri->segment(3);

        if ($this->form_validation->run() == FALSE) {
            $data['level'] = $this->usermodel->get_all_level();
            // dapatkan data user yg akan diedit dari database
            $data['user'] = $this->usermodel->get_user_by_id($id);
            $this->template->set('title', 'Edit User | MyWebApplication.com');
            $this->template->load('template', 'admin/form_edit_user', $data);
        } else {
            $data_user = array(
                'user_nama' => $this->input->post('nama'),
                'user_username' => $this->input->post('username'),
                'user_password' => md5($this->input->post('password')),
                'user_level' => $this->input->post('level')
            );
            $this->usermodel->update_data_user($data_user, $id);
            // kembalikan ke halaman manajemen user
            redirect('home/manajemen_user');
        }
    }

    function delete_user() {
        // mencegah user yang belum login untuk mengakses halaman ini
        $this->auth->restrict();
        // mencegah user mengakses menu yang tidak boleh ia buka (manejemen user menu_id = 2)
        $this->auth->cek_menu(2);
        // dapatkan id user dari segment ke-3 dari URI
        $id = $this->uri->segment(3);
        $this->usermodel->delete_user($id);
        // kembalikan ke halaman manajemen user
        redirect('home/manajemen_user');
    }

}